/**
 * 提示文本框
 * 调用方法：
 */

import React, { useState, useEffect, ReactElement } from 'react';
import { View, Text, DeviceEventEmitter } from 'react-native';

import { GLOBAL_TOOLTIP, TOOLTIP_TIMER } from '../../constant/index';
import Notch, { NotchType } from '../Notch';

import styles from './style';
import Log from '../../common/log';
import navigator from '../../util/navigator';
import { getRouteType, RouteType } from '../../config/route';

export interface ToolTipData {
  desc: string; // 提示文案
  visible?: boolean; // 是否显示
  time?: number; // 文案持续事件
}

const init = {
  desc: '',
  visible: false,
  time: TOOLTIP_TIMER
};

const ToolTip = (): ReactElement | null => {
  const [state, setState] = useState<ToolTipData>(init);
  const { desc, visible, time } = state;

  useEffect((): (() => void) => {
    let timer: number | null;
    const subscription = DeviceEventEmitter.addListener(
      GLOBAL_TOOLTIP,
      (param): void => {
        setState(param);

        if (timer) {
          clearTimeout(timer);
          timer = null;
        }

        if (param.visible) {
          timer = setTimeout((): void => {
            setState(init);
          }, param.time || time);
        }
      }
    );

    return (): void => {
      subscription.remove();
    };
  }, []);

  if (!visible) return null;

  const currentRoute = navigator.getCurrentRoute();
  const routeType = getRouteType(currentRoute.routeName);

  return (
    <Notch
      style={styles.container}
      type={routeType === RouteType.LandScape ? NotchType.Left : NotchType.Top}
    >
      <View style={styles.load}>
        <Text style={styles.desc}>{desc}</Text>
      </View>
    </Notch>
  );
};

export default ToolTip;
